package com.lostandfound.dao.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.lostandfound.dao.PlaceDao;
import com.lostandfound.entity.Place;

@Repository("placeDao")
public class PlaceDaoImpl implements PlaceDao {
	
	private Log logger = LogFactory.getLog(this.getClass());
	
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public Serializable save(Place obj) {
		logger.info("添加了一个丢失物品地点");
		return sessionFactory.getCurrentSession().save(obj);
	}

	@Override
	public void update(Place obj) {
		logger.info("修改了一个丢失物品地点");
		sessionFactory.getCurrentSession().update(obj);
	}

	@Override
	public void delete(Place obj) {
		logger.info("删除了一个丢失物品地点");
		sessionFactory.getCurrentSession().delete(obj);
	}

	@Override
	public Place selectByPrimary(Long id) {
		return (Place)sessionFactory.getCurrentSession().load(Place.class, id);
	}

	@Override
	public List<?> listPlaceByPage(Map<String, Object> pagemap) {
		List<?> list = null;
		Session session = sessionFactory.getCurrentSession();
		String hql = "from Place s where s.sstatus = '0' ";
		if(pagemap != null){
			if(pagemap.get("page") != null && !((String)pagemap.get("page")).equals("")
					 && pagemap.get("size") != null && !((String)pagemap.get("size")).equals("")){
				int page = Integer.parseInt((String)pagemap.get("page"));
				int size = Integer.parseInt((String)pagemap.get("size"));
				Query query = session.createQuery(hql)
						.setFirstResult((page-1)*size)
						.setMaxResults(size);
				list = query.list();
			}
		}
		return list;
	}

	@Override
	public void deletePlaceByBranch(Long[] places) {
		String hql = "";
		for(int i=0;i<places.length;i++) {
            if(i==0) {
                hql = "s.sid="+places[i];
            } else {
                hql =hql + " or s.sid="+places[i];
            }
        }
		if(!hql.equals("")){
	        Session session= sessionFactory.getCurrentSession();
	        Query q= session.createQuery("update Place s set s.sstatus = '1' where "+hql);
	        q.executeUpdate();
			logger.info("批量删除了丢失物品地点" + places);
		}
	}

	@Override
	public List<?> getAllPlace() {
		return sessionFactory.getCurrentSession()
				.createQuery("select s from Place s where s.sstatus = '0' ")
				.list();
	}

	@Override
	public int getCount() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("select count(*) from Place s where s.sstatus = '0' ");
		return ((Number) query.iterate().next())
	  	         .intValue();
	}
}
